package com.forte.categorydao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class CategoryDAOImpl implements CategoryDAO {
	
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	protected final Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}

	public void saveOrUpdate(Category category) {
		getCurrentSession().saveOrUpdate(category);		
	}

	@SuppressWarnings("unchecked")
	public Category findCategoryById(int categoryId) {
		Query query = getCurrentSession().createQuery(
				"from category where categoryId = :categoryId");
		query.setParameter("categoryId", categoryId);
		
		return foundCategory(query.list());		
	}
	
	public Category foundCategory(List<Category> list){
		Category catFound = null;
		if(list.size() > 0){
			catFound = (Category) list.get(0);			
		}
		return catFound;
	}

}
